<template>
  <div class="commen-container ">
    <div class="commen-header" style="display: flex; justify-content: space-between;align-items: center">
      <h2>教学团队</h2>
      <el-button type="success" size="normal" icon="el-icon-circle-plus" @click="handleAdd">
        新增
      </el-button>
    </div>
    <div v-if="!tableData || tableData.length < 1" class="juzhong">
      <span><i class="el-icon-loading"></i>
      加载中</span>
      <el-divider></el-divider>
    </div>
    <div v-else class="post-table">
      <div v-for="item in tableData" :key="item.tech_cour_id"
           class="item-container animate__animated animate__fadeIn"
      >
        <div class="item-content">
          <ul>
            <li>
              <h3>{{ item.username }}</h3>
              <div style="color: darkgrey">{{ item.english_name }}</div>
            </li>
            <li>
              <img
                :src="item.tech_pic"
                style="width: 300px;object-fit: cover"/>
            </li>
          </ul>
          <ul>
            <li>
              <h3>教师介绍：</h3>{{ item.intro }}
            </li>
            <!--            <li>-->
            <!--              <el-rate-->
            <!--                v-model="item.rating"-->
            <!--                disabled-->
            <!--                show-score-->
            <!--                text-color="#ff9900"-->
            <!--                score-template="{value}">-->
            <!--              </el-rate>-->
            <!--            </li>-->
          </ul>
        </div>
        <div class="juzhong operation"><p> 更新时间：{{
            item.update_time
          }}</p>
          <el-button @click="handleEdit(item)">修改</el-button>
          <el-button type="danger" @click="confirmDelete(item)">删除</el-button>
        </div>
      </div>
    </div>
    <!-- 新增/修改弹窗 -->
    <el-dialog
      title="新增/修改教师信息"
      :visible.sync="dialogVisible"
      width="50vw">
      <el-form :model="formData" label-width="80px">
        <el-form-item label="英文名">
          <el-input v-model="formData.english_name"></el-input>
        </el-form-item>

        <el-form-item label="教师电话">
          <el-input v-model="formData.phone_num"></el-input>
        </el-form-item>
        <el-form-item label="教师照片">
          <el-upload
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            :show-file-list="false"
            :auto-upload="true"
            :disabled="isUploadDisabled"
            action="http://113.45.144.121:1888/yxch/admin/upload"
          >
            <el-button type="primary" :loading="isUploadLoading">上传头像</el-button>
          </el-upload>
          <img ref="image" :src="formData.tech_pic" style="width: 100px; margin-top: 10px; object-fit: cover;">
        </el-form-item>
        <el-form-item label="教师介绍">
          <el-input
            type="textarea"
            :rows="7"
            v-model="formData.intro"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
        <!--        <el-form-item label="评分">-->
        <!--          <el-input v-model="formData.rating"></el-input>-->
        <!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {Message, MessageBox} from "element-ui";
import {getTeam, createOrUpdateTeacher, deleteTeacher} from "@/api/home/teacherteam";
import {uploadImage} from "@/api/commen";

export default {
  data() {
    return {
      tableData: null,
      dialogVisible: false,
      formData: {
        tech_cour_id: null, // 用于修改时存储记录的id
        username: '',
        english_name: '',
        tech_pic: '',
        intro: '',
        rating: '',
        phone_num: ''
      },
      isUploadDisabled: false, // 上传按钮禁用状态
      isUploadLoading: false // 上传按钮加载状态
    }
  },
  methods: {
    async fetchTable() {
      try {
        const rep = await getTeam({courseId: 1});
        this.tableData = rep;
      } catch (e) {
        console.log(e);
        Message.warning("查询无效！");
      }
    },
    handleAdd() {
      this.dialogVisible = true;
      this.formData = {
        phone_num: '',
        course_id: 1
      };
      this.isUploadDisabled = false;
      this.isUploadLoading = false;
    },
    handleEdit(row) {
      this.dialogVisible = true;
      this.formData = {
        tech_cour_id: row.tech_cour_id,
        username: row.username,
        english_name: row.english_name,
        tech_pic: row.tech_pic,
        intro: row.intro,
        rating: row.rating,
        phone_num: row.phone_num,
        course_id: 1
      };
      this.isUploadDisabled = false;
      this.isUploadLoading = false;
    },
    async handleSubmit() {
      try {
        await createOrUpdateTeacher(this.formData);
        Message.success('操作成功');
        this.dialogVisible = false;
        await this.fetchTable();
      } catch (e) {
        console.log(e);
        Message.warning('操作失败');
      }
    },
    async confirmDelete(row) {
      MessageBox.confirm('确定要删除该记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return this.handleDelete(row);
      }).then(() => {
        Message.success('删除成功');
        this.fetchTable();
      }).catch(() => {
        Message.info('已取消删除');
      });
    },
    async handleDelete(row) {
      try {
        await deleteTeacher(row.tech_cour_id);
      } catch (e) {
        console.log(e);
        Message.warning('删除失败');
      }
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }

      return isJPG && isLt2M;
    },

    // 上传成功处理
    handleUploadSuccess(response) {
      if (response.status === 1) {
        this.$message.success('上传成功!')
        // 更新头像显示 (假设response.data包含图片URL)
        this.formData.tech_pic = response.data
        this.$refs.image.src = response.data
        console.log(this.formData.tech_pic);

        // 检查DOM
        this.$nextTick(() => {
          console.log('图片元素:', this.$refs.image)
        })
      } else {
        console.log(response);
        this.$message.error(response.data.msg || '呜呜呜上传失败')
      }
    },

    // 上传错误处理
    handleUploadError(error) {
      console.error('上传失败:', error)
      this.$message.error('上传失败，请重试')
      console.error(err);
    }
  }

  ,
  mounted() {
    this.fetchTable();
  }
}
</script>

<style scoped lang="scss">
.item-container {
  position: relative;
  margin-top: 10px;
  padding: 10px;

  background: rgba(227, 238, 255, 0.24);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  border-radius: 10px;
}

.item-content {
  display: flex;

  li {
    margin: 5px;
  }
}

ul, li {
  list-style: none; /* 移除项目符号（如圆点、数字等） */
  margin: 5px; /* 移除默认的外边距 */
  padding: 0; /* 移除默认的内边距 */
}

.operation {
  position: absolute;
  right: 20px;
  bottom: 20px;
  flex-direction: row;
}
</style>
